<template>
  <!--数据同步配置-->
  <el-row style="height:100%">
    <page>
      <pageheader :event="'dataSyncAdd'" :isShow="true">
        数据同步配置
      </pageheader>
      <div class="page-content">
        <el-card class="box-card tag-card">
          <el-row>
            <SearchInput
              style="margin-left: 20px"
              @physSearch="physSearch"
              :searchEvent="'physSearch'"
              :value.sync="keywords"
              :searchText="'请输入关键字'"
              ref="clearText"
            >搜索：
            </SearchInput>
          </el-row>
           <el-table :data="dataTable" size="small" stripe class="data_sync_table">
              <el-table-column label="所属企业ID" prop="company_id" align="center" ></el-table-column>
              <el-table-column label="所属企业名称" prop="company_name" align="center" ></el-table-column>
              <el-table-column label="同步的账号" prop="syn_account" align="center" ></el-table-column>
              <el-table-column label="同步标识syn_开头" prop="syn_mark" align="center" ></el-table-column>
              <el-table-column label="最大执行数" prop="max_run_count" align="center" ></el-table-column>
              <el-table-column label="创建时间" prop="created_time" align="center" >
                 <template slot-scope="scope">{{getDate(scope.row.created_time)}}</template>
              </el-table-column>
              <el-table-column label="table_code" prop="table_code" align="center" ></el-table-column>
              <el-table-column label="验证密码" prop="syn_secret" align="center" width="260">
                <template slot-scope="scope">
                  <span v-show="scope.row.isShowSynSecret">{{scope.row.syn_secret }}</span>
                  <span v-show="!scope.row.isShowSynSecret">***********</span>
                  <el-button size="mini" @click="scope.row.isShowSynSecret = !scope.row.isShowSynSecret" style="margin-left: 20px">
                    <span v-show="scope.row.isShowSynSecret">隐藏</span>
                    <span v-show="!scope.row.isShowSynSecret">显示</span>
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="是否启用" align="center" >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.is_use == 1" size="mini" type="success">是</el-tag>
                  <el-tag v-else size="mini" type="danger">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="是否将根企业一起同步" align="center" >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.is_syn_parent == 1" size="mini" type="success">是</el-tag>
                  <el-tag v-else size="mini" type="danger">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" >
                <template slot-scope="scope">
                   <el-button size="small" @click="heatData(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination background
                           layout="total,sizes,prev,pager,next"
                           @current-change="currentChange"
                           @size-change="sizeChange"
                           :page-sizes="pagination.pageSizes"
                           :page-size.sync="pagination.pageSize"
                           :total="pagination.total"
                           :current-page.sync="pagination.currentPage"
                           class="paging fr">
            </el-pagination>
        </el-card>
        <el-dialog v-dialogDrag :title="dialogTitle+'数据同步'" :visible.sync="isShow" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="800px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="所属企业id" prop="company_id">
              <el-input v-model="ruleForm.company_id" size="small" :disabled="!isAdd"  style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="所属企业名称" prop="company_name">
              <el-input v-model="ruleForm.company_name"  size="small" :disabled="!isAdd" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="是否启用" prop="is_use">
                <el-switch active-text="启用"  inactive-text="未启用" v-model="ruleForm.is_use"  ></el-switch>
            </el-form-item>
            <el-form-item label="是否将根企业一起同步" prop="is_syn_parent ">
                <el-switch active-text="是"  inactive-text="否" :disabled="!isAdd" v-model="ruleForm.is_syn_parent"  ></el-switch>
            </el-form-item>
            <el-form-item label="要同步系统的根企业" prop="qiye">
              <Cascader :value.sync="ruleForm.company_id_arr"
                        :options="companyOptions"
                        :changeEvent="'companyChange'"
                        :width="'300px'"
                        :disabled="!isAdd"
                        :isClearable="true"></Cascader>
            </el-form-item>
            <el-form-item label="最大执行数" prop="max_run_count" >
              <el-input-number v-model="ruleForm.max_run_count" size="small" :disabled="!isAdd"  :min="0"   ></el-input-number>
            </el-form-item>
            <el-form-item label="同步帐号" prop="syn_account">
              <el-input v-model="ruleForm.syn_account" size="small" :disabled="!isAdd" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="syn_secret">
              <el-input v-model="ruleForm.syn_secret" size="small"  style="width:450px"></el-input>
            </el-form-item>
             <el-form-item label="同步标识syn_开头" prop="syn_mark">
              <el-input v-model="ruleForm.syn_mark" size="small" :disabled="!isAdd" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="当前案场所属table_code" prop="table_code">
              <el-input v-model="ruleForm.table_code" size="small" :disabled="!isAdd" style="width:450px"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <!--判断是否显示保存按钮：isDisabled 判断为是否为修改页面 -->
            <el-button type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    .tag-card{
      >.el-card__body{
        >.el-row{
          margin: 20px 0;
        }
      }
    }
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .data_sync_table{
    }
  }

</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import SearchInput from "@/components/sys/assembly/searchinput";
  import pageheader from "@/components/page/pageheader";
  import Cascader from "@/components/sys/assembly/elcascader";
  export default {
    data() {
      let validateCompanyId = (rule, value, callback)=>{
        if(!this.isAdd) return  callback();
        if (!value) {
          return callback(new Error('企业名不能为空'));
        }
        let url ='/syn/synchronize/account/get-synchronize-by-company-id?companyId='+ value;
        this.$api.get(url)
        .then(data =>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data.data){
            callback(new Error('ID已使用'));
          }else{
            callback();
          }
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
        })
      };
      let validateAccount = (rule, value, callback)=>{
        if(!this.isAdd) return callback();
        if (!value) {
          return callback(new Error('同步的帐号不能为空'));
        }
        let url ='/syn/synchronize/account/get-synchronize-by-account?account='+ value;
        this.$api.get(url)
        .then(data =>{
          if(data == '10001'){
            this.$message.error('无权操作该数据');
            this.$Bus.$emit('Loading',false);
          }
          if(data.data){
            callback(new Error('名称已使用'));
          }else{
            callback();
          }
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
        })
      }
      return {
        dataTable:[],
        keywords:'',
        pagination:{
          total:0,//总条目数
          currentPage:1,//当前页数
          pageSize:10,//每页显示条目个数
          pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
        },//表格分页参数
        ruleForm:{
          company_id:'',    //所属企业id
          company_name:'',  //所属企业名称 
          id:'',  //主键id
          is_use:true,   //是否启用 1启用 0未启用
          is_syn_parent :true, //是否将根企业一起同步，0 否；1是; 
          company_id_arr:[],  //要同步系统企业的数组   前端使用 不用传后台
          parent_company_id :'',  //要同步系统的根企业ID
          max_run_count:3,  //最大执行数
          syn_account:'', //同步的帐号,
          syn_mark:'',  //同步标识syn_开头，
          syn_secret:'',  //验证密码
          table_code:'', //当前案场所属table_code
        },
        companyOptions:[],
        dialogTitle:'',  //模态框标题
        isAdd:false,
        isShow:false, //新增/编辑 模态框
        rules: {
          company_id: [{ required: true,validator:validateCompanyId, trigger: "blur" }],
          company_name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
          max_run_count: [{ required: true, message: "请输入最大执行数", trigger: "blur" }],
          syn_account: [{ required: true,validator:validateAccount, trigger: "blur" }],
          syn_mark: [{ required: true, message: "请输入标识syn_开头", trigger: "blur" }],
          syn_secret: [{ required: true, message: "请输入验证密码", trigger: "blur" }],
          table_code: [{ required: true, message: "请输入当前案场所属table_code", trigger: "blur" }],
        },//form表单验证

      }
    },
    inject: ["reload"],
    components: {
      page,
      pageheader,
      SearchInput,
      Cascader,//级联选择器组件
    },
    created() {
      this.getDataList();
    },
    mounted() {
       //选择所属企业change事件
      this.$Bus.$on('companyChange',data =>{
        this.ruleForm.company_id_arr = data;
        this.ruleForm.parent_company_id=data.slice(-1)[0];
      });
      //点击新增按钮
      this.$Bus.$on("dataSyncAdd", () => {  
          this.isAdd=true;
          this.dialogTitle='新增';
          this.isShow=true;
          this.getCompanyTree();
      });
      
    },
    beforeDestroy(){
      this.$Bus.$off('companyChange');
    },
    methods: {
      //搜索按钮点击事件
      physSearch(data) {
        this.$Bus.$emit('Loading',true);
        this.keywords = data;
        this.getDataList(this.pagination.currentPage,this.pagination.pageSize,this.keywords);
      },
      //分页change事件
      currentChange(val){
        this.$Bus.$emit('Loading',true)
        this.pagination.currentPage=val;
        this.getDataList(this.pagination.currentPage,this.pagination.pageSize,this.keywords)
      },
      //每页显示条目个数change事件
      sizeChange(val){
        this.$Bus.$emit('Loading',true);
        this.getDataList(this.pagination.currentPage,val,this.keywords)
      },
      getDataList(page = 1,page_size = 10 ,keywords = ''){
        let url = '/syn/synchronize/account/list?keywords='+keywords+'&page='+page+'&page_size='+page_size;
        this.$api.get(url)
        .then(data =>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data){
            let _data = data.data;
            if(_data.dataList&&_data.dataList.length)
            {
              this.tableData = _data.dataList.map(x=>{
                x.isShowSynSecret = false
                return x
              })
            }
            this.dataTable = _data.dataList ? _data.dataList : [];
            this.pagination.total = _data.dataCount;
            this.pagination.currentPage = _data.pageCode;
            this.pagination.pageSize = _data.pageSize;
          }else{
            this.dataTable = [];
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.dataTable = []
          this.$Bus.$emit('Loading',false)
        });
      },
      //模态框保存按钮
      confirmDialog(formName){
        let dataV = {};
        let model = null;
        let url = ''
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$Bus.$emit('Loading',true);
            model = this.$refs[formName].model;
            dataV.company_id = model.company_id;
            dataV.company_name  = model.company_name ;
            dataV.is_use  = model.is_use?1:0;
            dataV.syn_account  = model.syn_account ;
            dataV.max_run_count = model.max_run_count;
            dataV.syn_mark  = model.syn_mark ;
            dataV.syn_secret = model.syn_secret;
            dataV.table_code = model.table_code;
            dataV.parent_company_id=model.parent_company_id;
            dataV.is_syn_parent  = model.is_syn_parent?1:0;
            if(this.isAdd){
              this.confirmAdd(dataV);
            }
            else{
              dataV.id=model.id;
              this.confirmUpdate(dataV);
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      //新增
      confirmAdd(dataV){
        let url='/syn/synchronize/account/create-synchronize';
        this.$api.post(url,dataV)
        .then(data=>{
          if(data&&data.code==0){
            this.reload();
            this.$message({
              message: "添加成功",
              type: "success"
            });
          }
          else{
            this.$message({
              message: "添加失败",
              type: "warning"
            });
          }
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
          console.log(err);
        })
      },
      //修改
      confirmUpdate(dataV){
        let url='/syn/synchronize/account/update-synchronize';
        this.$api.put(url,dataV)
        .then(data=>{
          if(data.code==0){
            this.reload();
            this.$message({
              message: "修改成功",
              type: "success"
            });
          }
          else{
            this.$message({
              message: "修改失败",
              type: "warning"
            });
          }
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
          console.log(err);
        })
      },
      //关闭模态框
      closeDialog(formName){
        this.ruleForm.company_id_arr=[];
        this.$refs[formName].resetFields();
        this.$Bus.$emit('Loading',false);
      },
      //详情
      heatData(data){
        this.$Bus.$emit('Loading',true);
        this.dialogTitle='修改';
        this.isAdd=false;
        this.isShow=true;
        let url='/syn/synchronize/account/get-synchronize?id='+data.id;
        this.$api.get(url)
        .then(data=>{
          if(data.data)
          {
            let _data=data.data;
            this.ruleForm.company_id = _data.company_id;
            this.ruleForm.company_name  = _data.company_name;
            this.ruleForm.parent_company_id=_data.parent_company_id;
            this.ruleForm.is_syn_parent=_data.is_syn_parent==1?true:false;
            this.ruleForm.is_use  = _data.is_use==1?true:false;
            this.ruleForm.max_run_count = _data.max_run_count;
            this.ruleForm.syn_account  = _data.syn_account ;
            this.ruleForm.syn_mark  = _data.syn_mark ;
            this.ruleForm.syn_secret = _data.syn_secret;
            this.ruleForm.table_code = _data.table_code;
            this.ruleForm.id=_data.id;
            this.getCompanyTree(true);
          }
          else{
           this.$message({
              message: "无数据",
              type: "warning"
            });
          }
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
        })
      },
      //格式化(date)时间
      getDate(date){
        return   moment(date).format('YYYY-MM-DD HH:mm:ss');
      },
      //获取企业树
      getCompanyTree(islook=false){
        this.$Bus.$emit('Loading',true);
        let url = '/sys/report_assist_new/company_tree';
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data){
            recursion(data.data);
            function recursion(val) {
              if(val.length){
                for(let i in val){
                  val[i].value = val[i].id;
                  val[i].label = val[i].company_name;
                  val[i].parent_id_str =val[i].parent_name_list==null?'':val[i].parent_name_list.join('/');
                  if(val[i].children && val[i].children.length){
                    recursion(val[i].children)
                  }else{
                    delete val[i].children
                  }
                }
              }
            }
            if(islook&&this.ruleForm.parent_company_id)
            {
              this.$nextTick(()=>{
                this.ruleForm.company_id_arr.push(this.ruleForm.parent_company_id);
                this.companyOptions = data.data;
              })

            }
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.companyOptions = [];
          this.$Bus.$emit('Loading',false)
        })
      },
    },
    watch: {}
  }
</script>
